// view-answer.js
import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
async function displayAnswers() {
    try {
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        const practiceId = urlParams.get('practiceId');
        const response = await fetch(`/user-info?username=${username}`);
        const data = await response.json();
        const userId = data.user_id;
        if (!username || !practiceId) {
            throw new Error('缺少必要的参数');
        }
        await setupUserProfile(username);
        // 获取练习详情
        const practiceDetail = await fetchPracticeDetail(practiceId, userId);
        document.getElementById('practice-title').textContent = practiceDetail.practice_name;
        document.getElementById('course-info').textContent = `所属课程：${practiceDetail.course_name}`;
        
        const userScore = await fetchUserScore(practiceId, userId);
        const totalScore = await fetchPracticeScore(practiceId);

        document.getElementById('user-score').textContent = `${userScore.totalScore}/${totalScore.data.total_score}`;

        // 获取题目答案
        const questionsContainer = document.getElementById('questions-container');
        questionsContainer.innerHTML = '';

        // 获取所有类型的题目
        const [choiceQuestions, fillQuestions, essayQuestions] = await Promise.all([
            fetchChoiceQuestions(practiceId, userId),
            fetchFillQuestions(practiceId, userId),
            fetchEssayQuestions(practiceId, userId)
        ]);

        // 为每种类型的题目添加type字段以便区分
        const choiceQuestionsWithType = choiceQuestions.map(q => ({...q, type: 'choice'}));
        const fillQuestionsWithType = fillQuestions.map(q => ({...q, type: 'fill'}));
        const essayQuestionsWithType = essayQuestions.map(q => ({...q, type: 'essay'}));

        // 合并所有题目并按题号排序
        const allQuestions = [
            ...choiceQuestionsWithType,
            ...fillQuestionsWithType,
            ...essayQuestionsWithType
        ].sort((a, b) => a.question_order - b.question_order);

        // 按排序后的顺序显示所有题目
        for (const question of allQuestions) {
            switch(question.type) {
                case 'choice':
                    await displaySingleChoiceQuestion(question, questionsContainer, practiceId, userId);
                    break;
                case 'fill':
                    await displaySingleFillQuestion(question, questionsContainer, practiceId, userId);
                    break;
                case 'essay':
                    await displaySingleEssayQuestion(question, questionsContainer, practiceId, userId);
                    break;
            }
        }

        // 添加返回按钮事件
        document.getElementById('back-btn').addEventListener('click', () => {
            window.location.href = 'todo-practice.html' + window.location.search;
        });
        document.getElementById('export-btn').addEventListener('click', exportPracticeRecord);
    } catch (error) {
        console.error('加载答案失败:', error);
        alert(`加载答案失败: ${error.message}`);
    }
}

// 显示单个选择题（修改后）
async function displaySingleChoiceQuestion(question, container, practiceId, userId) {
    const response = await fetch(`/check-question-collection?practiceId=${practiceId}&userId=${userId}&questionOrder=${question.question_order}`);
    const data = await response.json();
    let isCollected = data.isCollected;
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card';

    // 格式化选项
    const options = ['A', 'B', 'C', 'D'];
    let optionsHtml = '';

    options.forEach(option => {
        const isCorrect = question.correct_answer === option;
        const isSelected = question.user_answer === option;

        // 选项样式类
        let optionClass = 'p-3 rounded-md transition-all duration-300 flex items-start';
        if (isCorrect) optionClass += ' bg-green-50 border border-green-100';
        if (isSelected && !isCorrect) optionClass += ' bg-red-50 border border-red-100';

        // 选项前缀字母
        const optionLabel = `<span class="font-medium mr-2">${option}.</span>`;

        // 状态图标和提示
        let statusIcon = '';
        let statusText = '';
        
        if (isCorrect) {
            statusIcon = '<i class="fa-solid fa-check-circle text-green-500 mr-2"></i>';
            if (isSelected) {
                statusText = '<span class="text-green-600 text-sm">回答正确</span>';
            } else {
                statusText = '<span class="text-green-600 text-sm">正确答案</span>';
            }
        } else if (isSelected) {
            statusIcon = '<i class="fa-solid fa-xmark-circle text-red-500 mr-2"></i>';
            statusText = '<span class="text-red-600 text-sm">回答错误</span>';
        }

        // 构建选项HTML
        optionsHtml += `
            <div class="mb-3 ${optionClass}">
                <div class="flex items-center mb-1">
                    ${statusIcon}
                    ${optionLabel}
                </div>
                <div class="pl-6">
                    <p class="mb-1">${question[`option_${option.toLowerCase()}`]}</p>
                    ${statusText}
                </div>
            </div>
        `;
    });

    // 设置HTML内容（不包含收藏按钮）
    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-blue-50 rounded-xl border border-blue-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">选择题</h3>
            <span class="bg-white text-blue-600 rounded-full px-3 py-1 text-sm font-medium">${question.question_order + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
            ${escapeHTML(question.question)}
        </div>
        
        <ul class="space-y-3">
            ${options.map(option => {
                const isCorrect = question.correct_answer === option;
                const isSelected = question.user_answer === option;
                
                let optionClass = 'flex items-start bg-white/80 p-3 rounded-lg border';
                let iconClass = 'fa-circle-o text-gray-400';
                let borderClass = 'border-blue-100';
                let bgClass = '';
                
                if (isCorrect) {
                    optionClass += ' bg-green-50 border-green-500';
                    iconClass = 'fa-check-circle text-green-500';
                } else if (isSelected) {
                    optionClass += ' bg-red-50 border-red-500';
                    iconClass = 'fa-times-circle text-red-500';
                } else {
                    optionClass += ' border-blue-100';
                }
                
                return `
                <li class="${optionClass}">
                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">${option}</span>
                    <span>${escapeHTML(question[`option_${option.toLowerCase()}`])}</span>
                    <i class="fa-solid ${iconClass} ml-auto mt-1"></i>
                </li>
                `;
            }).join('')}
        </ul>
    </div>
    
    
    <!-- 得分信息 -->
    <div class="px-6 py-4 border-t border-blue-100 flex justify-between items-center">
        <div class="text-gray-600 font-medium">本题得分：</div>
        <div class="text-xl font-bold ${question.user_score !== null ? 'text-blue-600' : 'text-gray-500'}">
            ${question.user_score !== null ? question.user_score : '未评阅'}
        </div>
    </div>
</div>
    `;

    // 创建收藏按钮容器
    const collectSection = document.createElement('div');
    collectSection.className = 'collect-section';

    // 创建并添加收藏按钮
    const collectButton = await createCollectButton(question, practiceId, userId, isCollected);
    collectSection.appendChild(collectButton);

    // 将收藏按钮容器添加到问题卡片
    questionCard.appendChild(collectSection);

    // 将问题卡片添加到容器
    container.appendChild(questionCard);
}

async function displaySingleFillQuestion(question, container, practiceId, userId) {
    const response = await fetch(`/check-question-collection?practiceId=${practiceId}&userId=${userId}&questionOrder=${question.question_order}`);
    const data = await response.json();
    let isCollected = data.isCollected;
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card';

    // 解析填空题的空
    const blanks = [];
    let blankCount = 0;
    let totalScore = 0;
    let userTotalScore = 0;
   
    // 计算空白数量并生成问题文本
    const formattedQuestion = question.question.replace(/__/g, () => {
        blankCount++;
        return `<span class="inline-block mx-1 px-3 py-1 bg-green-50 border border-green-200 rounded text-sm">填空${blankCount}</span>`;
    });

    // 获取所有空的答案、分值和得分
    for (let i = 1; i <= blankCount; i++) {
        const isCorrect = question[`commited_answer${i}`] === question[`blank${i}_answer`];
        const hasUserAnswer = question[`commited_answer${i}`] !== undefined && question[`commited_answer${i}`] !== null;
        const blankScore = question[`blank${i}_score`] || 0;
        const userBlankScore = isCorrect ? blankScore : 0;

        blanks.push({
            correctAnswer: question[`blank${i}_answer`],
            userAnswer: question[`commited_answer${i}`],
            score: blankScore,
            userScore: userBlankScore,
            isCorrect: isCorrect,
            hasUserAnswer: hasUserAnswer
        });

        totalScore += blankScore;
        userTotalScore += userBlankScore;
    }

    // 生成填空答案HTML
    let blanksHtml = '';
    blanks.forEach((blank, blankIndex) => {
        // 答案状态样式
        let answerClass = 'bg-white/80 p-3 rounded-lg border';
        let iconClass = 'fa-circle-o text-gray-400';
        
        if (blank.hasUserAnswer && blank.isCorrect) {
            answerClass += ' bg-green-50 border-green-500';
            iconClass = 'fa-check-circle text-green-500';
        } else if (blank.hasUserAnswer && !blank.isCorrect) {
            answerClass += ' bg-red-50 border-red-500';
            iconClass = 'fa-times-circle text-red-500';
        } else {
            answerClass += ' border-blue-100';
        }

        blanksHtml += `
            <div class="mb-3 ${answerClass}">
                <div class="flex items-center">
                    <span class="bg-blue-100 text-blue-700 font-bold px-3 py-1 rounded mr-3">空${blankIndex + 1}</span>
                    <div class="flex-1">
                        <div class="flex items-center">
                            <span class="text-gray-700">${blank.hasUserAnswer ? blank.userAnswer : '未填写'}</span>
                            <i class="fa-solid ${iconClass} ml-auto"></i>
                        </div>
                        <div class="mt-2 flex justify-between text-sm">
                            <span class="text-gray-600">分值: ${blank.score}</span>
                            <span class="${blank.isCorrect ? 'text-green-600' : 'text-red-600'}">
                                ${blank.hasUserAnswer ? (blank.isCorrect ? '得分: ' + blank.userScore : '得分: 0') : '未评分'}
                            </span>
                        </div>
                        ${!blank.isCorrect && blank.hasUserAnswer ? 
                            `<div class="mt-1 text-sm text-green-600">
                                <i class="fa-solid fa-check-circle mr-1"></i> 正确答案: ${blank.correctAnswer}
                            </div>` : ''}
                    </div>
                </div>
            </div>
        `;
    });

    // 设置HTML内容
    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-green-50 rounded-xl border border-green-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-green-500 to-green-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">填空题</h3>
            <span class="bg-white text-green-600 rounded-full px-3 py-1 text-sm font-medium">${question.question_order + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-6 leading-relaxed">
            ${formattedQuestion}
        </div>
        
        <div class="answer-section">
            <div class="answer-label text-gray-600 font-medium mb-3">填空答案：</div>
            <div class="space-y-3">
                ${blanksHtml}
            </div>
        </div>
    </div>
    
    <!-- 底部信息栏 -->
    <div class="bg-green-50/70 px-6 py-4 border-t border-green-100">
        <div class="flex items-center justify-between pt-2 border-t border-green-100 mt-2">
            <span class="text-gray-600 font-medium">本题得分：</span>
            <span class="text-xl font-bold ${userTotalScore === totalScore ? 'text-green-600' : 'text-red-600'}">
                ${blanks.some(b => b.hasUserAnswer) ? userTotalScore : '未评阅'} / ${totalScore}
            </span>
        </div>
    </div>
</div>
    `;

    // 创建收藏按钮容器
    const collectSection = document.createElement('div');
    collectSection.className = 'collect-section';

    // 创建并添加收藏按钮
    const collectButton = await createCollectButton(question, practiceId, userId, isCollected);
    collectSection.appendChild(collectButton);

    // 将收藏按钮容器添加到问题卡片
    questionCard.appendChild(collectSection);

    // 将问题卡片添加到容器
    container.appendChild(questionCard);
}

// 显示单个解答题
async function displaySingleEssayQuestion(question, container, practiceId, userId) {
    const response = await fetch(`/check-question-collection?practiceId=${practiceId}&userId=${userId}&questionOrder=${question.question_order}`);
    const data = await response.json();
    let isCollected = data.isCollected;
    const questionCard = document.createElement('div');
    questionCard.className = 'question-card';

    // 设置HTML内容
    questionCard.innerHTML = `
<div class="bg-gradient-to-br from-white to-purple-50 rounded-xl border border-purple-100 shadow-md overflow-hidden mb-6">
    <!-- 标题栏 -->
    <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-3">
        <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold text-white">解答题</h3>
            <span class="bg-white text-purple-600 rounded-full px-3 py-1 text-sm font-medium">${question.question_order + 1}</span>
        </div>
    </div>
    
    <!-- 内容区 -->
    <div class="p-6">
        <div class="text-gray-700 text-lg mb-4 leading-relaxed">
            ${escapeHTML(question.question)}
        </div>
        
        <div class="answer-section">
            <div class="answer-label text-gray-600 font-medium mb-3">你的答案：</div>
            <div class="bg-white/80 p-4 rounded-lg border border-purple-100 mb-4">
                ${question.user_answer 
                    ? `<p class="text-gray-700">${escapeHTML(question.user_answer)}</p>` 
                    : '<p class="text-gray-500 italic">未填写</p>'}
            </div>
            
            ${question.sample_answer 
                ? `<div class="mt-4">
                    <div class="answer-label text-gray-600 font-medium mb-3">参考答案：</div>
                    <div class="bg-purple-50/50 p-4 rounded-lg border border-purple-200">
                        <p class="text-gray-700">${escapeHTML(question.sample_answer)}</p>
                    </div>
                   </div>`
                : ''}
        </div>
    </div>
    
    <!-- 得分信息 -->
    <div class="px-6 py-4 border-t border-purple-100 flex justify-between items-center">
        <div class="text-gray-600 font-medium">本题得分：</div>
        <div class="text-xl font-bold ${question.user_score !== null ? 'text-purple-600' : 'text-gray-500'}">
            ${question.user_score !== null ? question.user_score : '未评阅'}
        </div>
    </div>
</div>
    `;

    // 创建收藏按钮容器
    const collectSection = document.createElement('div');
    collectSection.className = 'collect-section';

    // 创建并添加收藏按钮
    const collectButton = await createCollectButton(question, practiceId, userId, isCollected);
    collectSection.appendChild(collectButton);

    // 将收藏按钮容器添加到问题卡片
    questionCard.appendChild(collectSection);

    // 将问题卡片添加到容器
    container.appendChild(questionCard);
}

// 创建收藏按钮
async function createCollectButton(question, practiceId, userId, isCollected) {
    const button = document.createElement('button');
    button.className = 'collect-btn';
    
    // 更新按钮外观的函数
    function updateButtonUI() {
        const starIcon = isCollected 
            ? '<i class="fa-solid fa-star text-red-500"></i>' 
            : '<i class="fa-regular fa-star text-gray-400"></i>';
        
        const buttonText = isCollected ? '取消收藏' : '收藏题目';
        button.innerHTML = `${starIcon} ${buttonText}`;
    }
    
    // 初始化按钮外观
    updateButtonUI();
    button.style.color = 'gray';

    button.addEventListener('click', async () => {
        try {
            let response, data;
            
            if (isCollected) {
                // 取消收藏
                response = await fetch('/uncollect-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        practiceId,
                        userId,
                        questionOrder : question.question_order
                    })
                });
                
                data = await response.json();
                
                if (response.ok) {
                    isCollected = false; // 更新状态
                    updateButtonUI();    // 更新UI
                } else {
                    alert(data.message);
                }
            } else {
                // 收藏题目
                response = await fetch('/collect-question', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        practiceId,
                        userId,
                        questionOrder: question.question_order
                    })
                });
                
                data = await response.json();
                
                if (response.ok) {
                    isCollected = true;  // 更新状态
                    updateButtonUI();    // 更新UI
                } else {
                    alert(data.message);
                }
            }
        } catch (error) {
            console.error('收藏操作失败:', error);
            alert('操作失败，请稍后重试');
        }
    });

    return button;
}

// 获取练习详情
async function fetchPracticeDetail(practiceId, userId) {
    const response = await fetch(`/practice/detail/${practiceId}?userId=${userId}`);
    const practice = await response.json();
    
    // 获取课程信息
    const courseResponse = await fetch(`/get-course/${practice.course_code}`);
    const course = await courseResponse.json();
    
    return { ...practice, course_name: course.course_name };
}

async function fetchUserScore(practiceId, userId) {
    const response = await fetch(`/calculate-total-score?userId=${userId}&practiceId=${practiceId}`);
    return await response.json();
}

async function fetchPracticeScore(practiceId) {
    const response = await fetch(`/api/practice/${practiceId}/total-score`);
    return await response.json();
}

async function fetchChoiceQuestions(practiceId, userId) {
    const response = await fetch(`/api/choice-questions/${practiceId}?userId=${userId}`);
    return await response.json();
}

async function fetchFillQuestions(practiceId, userId) {
    const response = await fetch(`/api/fill-questions/${practiceId}?userId=${userId}`);
    return await response.json();
}

async function fetchEssayQuestions(practiceId, userId) {
    const response = await fetch(`/api/essay-questions/${practiceId}?userId=${userId}`);
    return await response.json();
}

window.onload = async function() {
    try {
        await displayAnswers();
    } catch (error) {
        console.error('加载答案失败:', error);
        alert(`加载答案失败: ${error.message}`);
    }
};

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='todo-practice.html'+window.location.search;
        });
    }
});

// 导出练习记录为图片
async function exportPracticeRecord() {
    try {
        // 显示加载提示
        const loadingToast = showLoadingToast('正在生成练习记录图片...');
        
        // 获取要导出的内容区域 - 使用更可靠的选择器
        const exportElement = document.getElementById('questions-container'
        );
                
                if(!exportElement) {
                    throw new Error('找不到要导出的内容区域');
                }
        
        // 设置html2canvas选项
        const options = {
            scale: 2, // 提高导出图片的分辨率
            logging: false,
            useCORS: true,
            allowTaint: true,
            scrollX: 0,
            scrollY: 0,
            windowWidth: exportElement.scrollWidth,
            windowHeight: exportElement.scrollHeight,
            backgroundColor: '#FFFFFF'
        };
        
        // 使用html2canvas生成图片
        const canvas = await html2canvas(exportElement, options);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.download = `练习记录_${document.getElementById('practice-title').textContent}_${new Date().toLocaleDateString()}.png`;
        link.href = canvas.toDataURL('image/png');
        link.click();
        
        // 隐藏加载提示
        hideLoadingToast(loadingToast);
        
        // 显示成功提示
        showSuccessToast('练习记录导出成功！');
    } catch (error) {
        console.error('导出练习记录失败:', error);
        showErrorToast('导出练习记录失败，请重试');
    }
}

// 显示加载提示
function showLoadingToast(message) {
    const toastId = 'loading-toast-' + Date.now();
    const toast = document.createElement('div');
    toast.id = toastId;
    toast.className = 'fixed top-4 right-4 z-50';
    toast.innerHTML = `
        <div class="bg-dark text-white px-6 py-3 rounded-lg shadow-lg flex items-center">
            <div class="animate-spin mr-3">
                <i class="fa-solid fa-spinner"></i>
            </div>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    return toastId;
}

// 隐藏加载提示
function hideLoadingToast(toastId) {
    const toast = document.getElementById(toastId);
    if (toast) {
        toast.remove();
    }
}

// 显示成功提示
function showSuccessToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 z-50 animate-fade-in';
    toast.innerHTML = `
        <div class="bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg flex items-center">
            <i class="fa-solid fa-check-circle mr-3"></i>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    
    // 3秒后自动消失
    setTimeout(() => {
        toast.classList.add('animate-fade-out');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// 显示错误提示
function showErrorToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 z-50 animate-fade-in';
    toast.innerHTML = `
        <div class="bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg flex items-center">
            <i class="fa-solid fa-exclamation-circle mr-3"></i>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    
    // 3秒后自动消失
    setTimeout(() => {
        toast.classList.add('animate-fade-out');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// 在view-answer.js文件顶部添加这个函数
function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    if (!str) return '';
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

document.getElementById('header-back-btn').addEventListener('click', function() {
    window.location.href = 'todo-practice.html'+window.location.search;
});

export{
    escapeHTML,
    fetchPracticeDetail,
    fetchUserScore,
    createCollectButton,
    showLoadingToast,
    hideLoadingToast,
    showSuccessToast,
    showErrorToast,
    exportPracticeRecord,
}